<template>
  <body>
  <Layout id="mainpage">
    <div class="left-content">
      <div id="inputArea">
        <div class="headerWord">
          <span class="title-text">
            外规输入
            <el-popover
              placement="right"
              title="外规输入"
              :width="200"
              trigger="hover"
              content="普通匹配：直接分词后匹配内规；图谱拓展匹配：对分词结果进行图谱拓展，对‘分词结果+拓展结果’进行内规匹配。"
            >
              <template #reference>
                <img src="../../public/提示.svg" alt="">
              </template>
            </el-popover>
          </span>
          
          <input type="file" @change="loadTextFromFile" id="txt" style="display:none" />
            <div id="txtBtn1">
            </div>
          <el-button class="txtBtn" @click="importFakeData">测试模式</el-button>
          <el-button class="txtBtn" @click="importTXT">导入txt文件</el-button>
        </div>
        <div class="inputArea-matchText">
          <el-input
              v-model="matchText"
              :rows="8"
              type="textarea"
              class="inputMatchText"
              placeholder="请输入外规"
              input-style="background-color:transparent;color:white;height:100%"
              id="input-element"
          />
        </div>

        <div class="buttonArea">
          <el-button class="btn-item" @click="clearMatchText">清空</el-button>
          <el-button class="btn-item" @click="getNormalData">普通匹配</el-button>
          <el-button class="btn-item" @click="getGraphData">图谱拓展匹配</el-button>
        </div>
      </div>

      <div id="cloudBox" v-if="clickNormalButton">
        <div class="cloudHeader">
          <p class="title-text">
            词云图
            <el-popover
              placement="right"
              title="词云图"
              :width="200"
              trigger="hover"
              content="点击‘普通匹配’，对输入的外规进行分词，根据分词结果的重要程度，得到词云图。"
            >
              <template #reference>
                <img src="../../public/提示.svg" alt="">
              </template>
            </el-popover>
          </p>
        </div>

        <div id="cloud-container" class="left-down-box"
             v-loading="loading"
             element-loading-text="拼命加载中"
             element-loading-background="rgba(0, 0, 0, 0.8)"
        >
        </div>
      </div>

      <div id="cloudBox"
           v-if="! clickNormalButton"
      >
        <p class="title-text">图谱拓展词
          <el-popover
              placement="right"
              title="图谱拓展词"
              :width="200"
              trigger="hover"
              content="点击‘图谱拓展匹配’，对输入的外规进行分词，对分词结果的进行图谱拓展，得到关联词。"
            >
              <template #reference>
                <img src="../../public/提示.svg" alt="">
              </template>
            </el-popover>
        </p>
        <div class="left-down-box"
             v-loading="loading"
             element-loading-text="拼命加载中"
             element-loading-background="rgba(0, 0, 0, 0.8)"
        >
          <div v-for="item in graphExtendWord" :key="item[0]" class="extendWord-line">
            <el-button class="btn-item" style="width:25%;float:left;" @click="searchWord(item[0])">{{item[0]}}</el-button> 
            <span style="float:left;font-size:20px;display: flex;">=></span>
            <el-button class="btn-item" style="width:60%;float:left;">{{item[1]}} 、 {{item[2]}}</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- ===================内规匹配 或者 空界面================ -->
    <div class="right-content" v-if="this.showWhat === this.EMPTYBLOCKVIEW || this.showWhat === this.LISTVIEW">
      <div class="headerWord">
        <p class="title-text">内规匹配
          <el-popover
              placement="top-start"
              title="内规匹配"
              :width="200"
              trigger="hover"
              content="根据相似度从高到低排列。可勾选后加入‘我的内规’"
            >
              <template #reference>
                <img src="../../public/提示.svg" alt="">
              </template>
            </el-popover>
        </p>
        <el-button class="txtBtn" @click="jumpMyLaw" style="float:right;">我的内规</el-button>
      </div>

      <!-- 空界面 -->
      <div v-if="this.showWhat === this.EMPTYBLOCKVIEW" id="emptyListBlock">
        <br><br>
        <p class="pureText">点击的左侧匹配按钮，请求数据，使用愉快！</p>
      </div>

      <!-- 内规匹配 -->
      <div class="right-content-list"
           v-if="this.showWhat === this.LISTVIEW"
           v-loading="loading"
           element-loading-text="拼命加载中"
           element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <div class="law-box-div" v-for="data in showData" :key="data.id">
            <law-box :law-cont="data" @boxOnClick="openItem" @checkChange="checkChange"/>
        </div>
      </div>
      <div class="pagination">
        <el-pagination v-model:current-page="currentPage"
                       :page-size="lawBoxNum"
                       layout="total, prev, pager, next"
                       :total="allData.length"
                       @current-change="handleCurrentChange"
                       style="position: relative;left: 5%; top:10px;"
                       v-if="this.showWhat === this.LISTVIEW"
        />
      </div>

    </div>


    <!-- ========================我的内规界面==================== -->
    <div class="right-content" v-if="this.showWhat === this.MYLAWVIEW">
      <div class="headerWord">
        <p class="title-text">
          内规匹配 > 我的内规
          <el-popover
              placement="top-start"
              title="我的内规"
              :width="200"
              trigger="hover"
              content="取消勾选，可以从我的内规中删除"
            >
              <template #reference>
                <img src="../../public/提示.svg" alt="">
              </template>
            </el-popover>
        </p>
        <div id="txtBtn1">
        </div>
        <el-button class="txtBtn" @click="backToListPage" style="float:right;">返回</el-button>
        <el-button class="txtBtn" @click="importAllMyLaw" style="float:right;">全部导出</el-button>
      </div>
      <div class="right-content-list">
        <div class="law-box-div" v-for="data in showData" :key="data.id">
          <law-box :law-cont="data" v-if="data.isSelect" @boxOnClick="openItem" @checkChange="checkChange"/>
        </div>
      </div>
      <el-pagination v-model:current-page="currentPageOfMyLaw"
                     :page-size="lawBoxNum"
                     layout="total, prev, pager, next"
                     :total="mydatalist.length"
                     @current-change="handleMyLawChange"
                     style="position: relative;left: 40px; top:10px"
      />
    </div>


    <!-- ==================内规编辑界面====================== -->
    <div class="right-content" v-if="this.showWhat === this.DETAILVIEW">
      <div class="headerWord">
        <span class="title-text">
          内规匹配 > 内规编辑
          <el-popover
              placement="top-start"
              title="内规编辑"
              :width="200"
              trigger="hover"
              content="点击‘保存’，直接添加到‘我的内规’；编辑内容后自动加入‘我的内规’"
            >
              <template #reference>
                <img src="../../public/提示.svg" alt="">
              </template>
            </el-popover>
        </span>
        <div id="txtBtn1">
        </div>
        <el-button @click="backToListPage" class="txtBtn" style="float:right; ">返回</el-button>
        <el-button @click="importLaw" class="txtBtn" style="float:right; ">导出</el-button>
      </div>
      <div id="editOuter" >
        <div>
          <span style="color:white;">{{ mydatalist[editLawId.indexInMyDataList].lawTitle }}</span>
          <span style="float:right;color:white;" v-if="! contentChanged" > 😐未修改 </span>
          <span style="float:right;color:white;" v-if="contentChanged"> 😀已修改 </span>
        </div>
        <el-input
            v-model="this.mydatalist[this.editLawId.indexInMyDataList].lawContent"
            :rows="22"
            type="textarea"
            placeholder="内规编辑"
            id="editBlock"
            style="margin-top: 10px;"
            input-style="background-color:transparent;color:white;height:90%"
            @input="contentChange"
        />
        <div style="float:right;margin-right: 1%;margin-top: -20px;">
          <el-button @click="backToDefault">恢复默认</el-button>
          <el-button @click="store">保存</el-button>
        </div>
      </div>
    </div>

  </Layout>
  </body>

</template>
<script>
import Layout from "../components/Layout.vue";
import LawBox from "../components/LawBox.vue";
//练健恒的假数据
import {falseData} from "../stub/stubData";
//请求丰丰的测试数据
import {getNormalMatchData, getExGraphData} from '../network/index'

//注意这里需要下载一个npm install file-saver --save
import {saveAs} from 'file-saver';
//注意这里需要下载一个npm install highcharts@7.2.1,实现云图
import Highcharts from "highcharts/highcharts";
import wordcloud from "highcharts/modules/wordcloud";
wordcloud(Highcharts);
//树形图
import TreeChart from "vue-tree-chart";

export default {
  name: "lawmatch",
  components: {Layout, LawBox},
  data(){
    return {
      turnOn : localStorage.getItem("light"),
      // matchText: "近几年，银行保险机构积极开展数字化转型。与此同时，部分银行保险机构对信息科技外包风险管控不力，因而导致的业务中断、敏感信息泄露等事件时有发生。此外，部分领域外包服务提供商高度集中，形成了行业集中度风险。拟通过制定《办法》，从信息科技外包治理、准入、监控评价、风险管理等方面对银行保险机构信息科技外包提出要求。",
      matchText: "不断完善统一授信管理制度。健全客户信用风险识别与监测体系，不断完善授信决策与审批机制，采取有效措施防止对单一客户、关联企业客户和集团客户授信风险的高度集中，防止违反信贷原则发放关系人贷款和人情贷款，防止信贷资金违规使用。",
      //加载动画
      loading: false,
      //最初默认展示"普通匹配"-词云图
      clickNormalButton:true,
      //图谱拓展词
      graphExtendWord:[],

      //内规匹配list界面的当前页码
      currentPage: 1,
      //我的内规list界面的当前页码
      currentPageOfMyLaw: 1,
      //每页几个lawbox
      lawBoxNum: 4,
      //全部内规(原始内容、一直不能变)
      allData: [],
      //当前页面的内规
      showData: [],
      //我的内规
      //#region
      mydatalist: [],
      //#endregion
      editLawId:
          {
            //注意此处和lawId不一样，此处是数组的序号
            indexInAllData: -1, //初始赋值为-1
            indexInMyDataList: -1,
          },
      //
      contentChanged: false,

      // 笨办法切换右边的视图，路由跳转惹不起惹不起（花了一天也没搞定）
      EMPTYBLOCKVIEW: 1, //空的时候
      LISTVIEW: 2, //展示内规匹配结果列表
      MYLAWVIEW: 3, //我的内规
      DETAILVIEW: 4,  //详情编辑界面
      // 当前界面
      showWhat : 1
    }
  },
  mounted() {
    // if (this.turnOn === false){
    //   const inputArea = document.getElementById("textArea");
    //   inputArea.input-style.backgroundColor="white";
    //   // document.body.className = 'light';
    // }
  },
  computed(){
    // inputMatchText(){
    //   return this.blackShopExist?'black-shop-input':'';
    // }
  },
  methods:{
    // ================以下是左半部分的方法=====================
    //#region 左上部分的方法
    clearMatchText(){
      this.$confirm('确认清空？', {
         distinguishCancelAndClose: true,
         confirmButtonText: '确认',
         cancelButtonText: '取消', //相当于 取消按钮
         type: 'warning'
     }).then(what => {
        if(what === 'confirm'){
          this.matchText = '';
          this.showWhat = this.EMPTYBLOCKVIEW;
          this.clickNormalButton = true;
          document.getElementById('cloud-container').innerHTML = ''
          console.log('清空-确认');
        }
     }).catch(action => {
        //判断是 cancel (自定义的取消) 还是 close （关闭弹窗）
        console.log('error:',action);
     })
    },

    getNormalData(e){
      //请求之前跳转界面 && 开启加载动画
      this.showWhat = this.LISTVIEW;
      this.clickNormalButton = true;
      this.loading = true;
      //请求数据
      getNormalMatchData({"requestTxt": this.matchText}).then(res => {
        var dataList = res.normalMatchReturn;
        // 数组中的字符串转为json
        for (let i = 0; i < dataList.length; i++) {
          dataList[i] = eval('(' + dataList[i] + ')');
        }
        //把处理后的数据存到allData里面
        this.allData = dataList;
        this.showData = dataList.slice(0, this.lawBoxNum);
        //生成云图
        this.dealData(res.wordSegWeight)
        // 关闭加载动画
        this.loading = false;
      },
        error => {alert(error);}
      );

    },
    getGraphData(){
      //请求之前跳转界面 && 开启加载动画
      this.showWhat = this.LISTVIEW;
      this.clickNormalButton = false;
      this.loading = true;
      //请求数据
      getExGraphData({"requestTxt": this.matchText}).then(res => {
        // console.log(res.normalMatchReturn);
        var dataList = res.exGraphReturn;
        // 数组中的字符串转为json
        for (let i = 0; i < dataList.length; i++) {
          dataList[i] = eval('(' + dataList[i] + ')');
        }
        //把处理后的数据存到allData里面
        this.allData = dataList;
        this.showData = dataList.slice(0, this.lawBoxNum);

            //生成 图谱拓展词-列表
            this.graphExtendWord = res.extendedWord;
            // 关闭加载动画
            this.loading = false;
          },
          error => {alert(error);}
      )
    },
    //以下三个方法用于导入txt文件
    importTXT(){
      document.getElementById("txt").click();
    },
    loadTextFromFile(e) {
      const file = e.target.files[0];
      let name = file.name.split(".").splice(-1).toString();
      if (name !== "txt") {
        this.$message.success("文件类型错误,请重新选择文件");
        return;
      }
      const reader = new FileReader();
      if (typeof FileReader === "undefined") {
        alert("您的浏览器不支持FileReader接口");
      }
      reader.onload = (e) => this.$emit("load", this.dealNum(e.target.result));
      reader.readAsText(file, "utf-8");
    },
    dealNum(item) {
      this.matchText = item;
      console.log(item);
    },
    //测试模式
    importFakeData(){
      this.showWhat = this.LISTVIEW;
      this.clickNormalButton = false;
      var dataList = falseData.exGraphReturn;
      // 数组中的字符串转为json
      for (let i = 0; i < dataList.length; i++) {
        dataList[i] = eval('(' + dataList[i] + ')');
      }
      //把处理后的数据存到allData里面
      this.allData = dataList;
      this.showData = dataList.slice(0, this.lawBoxNum);

      //生成 图谱拓展词-列表
      this.graphExtendWord = falseData.extendedWord;
    },
    //#endregion

    //#region 左下部分的方法

    searchWord(text){
      window.find(text);
      console.log(window.find(text));
      // oP.innerHTML=oP.innerHTML.split(str).join('<span>'+str+'</span>')
    },
    dealData(jsonObj){
      let data = [];
      for(var key in jsonObj){
        var newObj = {
          name: key,
          weight: jsonObj[key] * 100
        }
        data.push(newObj);
      }
      this.drawPic(data);
    },
    drawPic(data){
      Highcharts.chart('cloud-container', {
        //highcharts logo
        credits: { enabled: false },
        //导出
        exporting: { enabled: false },
        //提示关闭
        tooltip: { enabled: false },
        //颜色配置
        colors:[
          // '#ffffff',
          '#00c0d7','#2594ce','#de4c85',
          '#ff7f46','#ffb310','#e25c52'
        ],
        //图形配置
        chart: {
            // spacingBottom: 15,
            // spacingTop: 12,
            spacingLeft: 5,
            spacingRight: 3,
            backgroundColor: 'transparent',//"rgba(255, 255, 255,0)"
            // width: 1000,
			      height: 240
        },
        series: [{
          type: "wordcloud",// 类型
          data: data,
          rotation: 90,//字体不旋转
          maxFontSize: 18,//最大字体
          minFontSize: 3,//最小字体
          style: {
            fontFamily: "sans-serif",
            fontWeight: '500'
          }
        }],
        title: { text: undefined },
        subtitle: { text: undefined }
      });
    },
    //#endregion
    // ================左半部分的方法结束=====================

    // ================以下是"内规匹配"界面的方法=====================
    handleCurrentChange(){
      this.showData = this.allData.slice(this.currentPage*this.lawBoxNum - this.lawBoxNum, this.currentPage*this.lawBoxNum)
    },
    //点击 => 进入”内规编辑界面“
    openItem(id){
      console.log("【打开】你点击了："+id);
      let index1 = this.existInAllData(id);
      let index2 = this.existInMyLaw(id);
      if (index1 === -1) {
        console.log("[error]: 数据不在allData中");
      }else{
        this.editLawId.indexInAllData = index1
        if(index2 === -1){
          //偷个懒，直接加进去mydatalist
          this.allData[index1].isSelect = true
          var newObj = JSON.parse(JSON.stringify(this.allData[index1])) 
          console.log("是不是新的对象？",newObj === this.allData[index1])
          newObj.isSelect = true
          this.mydatalist.push(newObj)

          this.editLawId.indexInMyDataList = this.mydatalist.length - 1
        }else{
          this.editLawId.indexInMyDataList = index2
        }
        // 初始化，显示😐未修改
        this.contentChanged = false
        // 跳转“内规编辑”界面
        this.showWhat = this.DETAILVIEW;
      }
    },
    //勾选/取消勾选 => 添加/删除我的内规
    checkChange(id, checkFlag){
      console.log("【添加、删除我的内规】你点击了：" + id + ",勾选情况：" + checkFlag );
      if (! checkFlag) {
        //若是不在我的内规，添加
        var newObj = JSON.parse(JSON.stringify(this.getDataFromAllData(id)));
        console.log("是不是新的对象？",newObj === this.getDataFromAllData(id));
        newObj.isSelect = true
        this.mydatalist.push(newObj)
        this.$alert('勾选代表添加到了“我的内规”中，赶紧去看看吧！', '添加成功！', {
          confirmButtonText: '确定',
          callback: action => {
            this.$message({
              type: 'info',
              message: `添加成功！`
            });
          }
        });
      }else{
        //若是在我的内规，删除
        let index = this.existInMyLaw(id)
        if(index === -1){
          console.log("删除失败，不存在 lawId = " + id + " 的数据");
        }else{
          this.mydatalist.splice(index, 1)
          console.log("删除了我的内规中的" + this.getDataFromAllData(id));
        }
        // alert("取消勾选代表从”我的内规“中删除，删除完成！")
        this.$alert('取消勾选代表从“我的内规”中删除，删除完成！', '删除成功！', {
          confirmButtonText: '确定',
          callback: action => {
            this.$message({
              type: 'info',
              message: `删除成功！`
            });
          }
        });
      }
    },

    //返回数据在allData中的序号，不存在返回-1
    existInAllData(id){
      for (let i = 0; i < this.allData.length; i++) {
        const data = this.allData[i];
        if (data.lawId === id) {
          // console.log();
          return i
        }
      }
      return -1
    },
    //返回数据在mydatalist中的序号，不存在返回-1
    existInMyLaw(id){
      for (let i = 0; i < this.mydatalist.length; i++) {
        const data = this.mydatalist[i];
        if (data.lawId === id) {
          return i
        }
      }
      return -1
    },
    //通过id返回数据在allData中的data，不存在返回-1
    getDataFromAllData(id){
      for (let i = 0; i < this.allData.length; i++) {
        const data = this.allData[i];
        if (data.lawId === id) {
          // console.log();
          return data
        }
      }
      return -1
    },
    //通过id返回数据在mydatalist中的data，不存在返回-1
    getDataFromMyLaw(id){
      for (let i = 0; i < this.mydatalist.length; i++) {
        const data = this.mydatalist[i];
        if (data.lawId === id) {
          // console.log();
          return data
        }
      }
      return -1
    },


    // ================以下是"我的内规"界面的方法=====================
    jumpMyLaw(){
      this.showWhat = this.MYLAWVIEW
      this.showData = this.mydatalist.slice(0,this.lawBoxNum)
    },
    handleMyLawChange(){
      this.showData = this.mydatalist.slice(this.currentPageOfMyLaw*this.lawBoxNum - this.lawBoxNum, this.currentPageOfMyLaw*this.lawBoxNum)
    },

    //导出所有”我的内规“条目
    importAllMyLaw(){
      for (let i = 0; i < this.mydatalist.length; i++) {
        const everyMyData = this.mydatalist[i];
        var txt = everyMyData.lawTitle + "\r\n\r\n" + everyMyData.lawContent
        let str = new Blob([txt], {type: 'text/plain;charset=utf-8'});
        // 注意这里要手动写上文件的后缀名
        saveAs(str, everyMyData.lawId + '-' + everyMyData.lawTitle + "[我的内规].txt");
      }
    },

    // ================以下是"内规编辑"界面的方法=====================
    //返回"内规匹配"界面
    backToListPage(){
      this.showWhat = this.LISTVIEW
      this.showData = this.allData.slice(this.currentPage*this.lawBoxNum - this.lawBoxNum, this.currentPage*this.lawBoxNum)
    },
    //导出
    importLaw(){
      let edited = this.mydatalist[this.editLawId.indexInMyDataList]
      var data = edited.lawTitle + "\r\n\r\n" + edited.lawContent
      let str = new Blob([data], {type: 'text/plain;charset=utf-8'});
      // 注意这里要手动写上文件的后缀名
      saveAs(str, edited.lawId + '-' + edited.lawTitle + "[我的内规].txt");
    },
    //恢复默认
    backToDefault(){
      console.log(this.mydatalist[this.editLawId.indexInMyDataList].lawContent);
      console.log(this.allData[this.editLawId.indexInAllData].lawContent);
      this.mydatalist[this.editLawId.indexInMyDataList].lawContent = this.allData[this.editLawId.indexInAllData].lawContent
    },
    //保存
    store(){
      //内容恢复默认
      this.contentChanged = false;
      //弹窗
      this.$alert('保存在了“我的内规”中，赶紧去看看吧！', '保存成功！', {
            confirmButtonText: '确定',
            callback: action => {
              this.$message({
                type: 'info',
                message: `保存成功！`
              });
            }
          });
    },
    contentChange(){
      this.contentChanged = true
      console.log("内容改变了");
    },

  },
  watch:{
  },
}
</script>

<style scoped>

@import "../css/lawmatch.css";
@import "../css/lawmatch_color.css";

</style>


